package com.paradogs.demo.login.controller;

import com.paradogs.framework.common.pojo.cg.CGLogin;
import com.paradogs.framework.common.pojo.cg.CGPrepareLogin;
import com.paradogs.demo.login.rpc.GateClient;
import com.paradogs.demo.login.rpc.MasterClient;
import com.paradogs.framework.common.dao.PlayerDao;
import com.paradogs.framework.common.entity.Player;
import com.paradogs.framework.common.pojo.gc.GCAllocGateway;
import com.paradogs.framework.common.pojo.gc.GCApplyGate;
import com.paradogs.framework.core.annoations.request.PRController;
import com.paradogs.framework.core.annoations.request.PRMsgMapping;
import com.paradogs.framework.core.msg.GCAck;
import com.paradogs.framework.core.utils.PRAsync;
import com.paradogs.framework.core.utils.Wrap;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.atomic.AtomicLong;

/**
 * @author: yumi
 * @date: 2023/11/13  14:33
 * @Description: TODO
 */
@Slf4j
@PRController
public class LoginController {

    @Autowired
    private MasterClient masterClient;

    @Autowired
    private GateClient gateClient;

    @Autowired
    private PlayerDao playerDao;

    @PRMsgMapping(value = "login", async = true)
    public GCApplyGate login(CGLogin dto) {
        Player player = playerDao.getOne(Wrap.<Player>lbq()
                .eq(Player::getAccount, dto.getAccount())
                .eq(Player::getPwd, dto.getPassword()));

        if (player == null) {
            GCAck.fail();
        }

        log.info("!!! 玩家登录成功: {}, {}", player.getAccount(), player);

        // 申请一个可以连接的网关
        GCAllocGateway gcAllocGateway = masterClient.allocGate();

        // 网关服准备登录信息
        String token = UUID.randomUUID().toString();
        gateClient.prepareLogin(new CGPrepareLogin(player.getUid(), token));
        GCApplyGate gc = new GCApplyGate(gcAllocGateway.getHost(), gcAllocGateway.getPort(), token);

        // 返回连接地址
        return gc; // 这个是发给客户端的，而不是发给服务器的，要特殊处理
    }

}
